package com.xboss.tv.net;

import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.xboss.tv.bean.Contacts;
import com.xboss.tv.listener.DataAPIListener;
import com.xboss.tv.listener.JsonCallback;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;

import java.util.Iterator;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by Administrator on 2017/7/14.
 */

public class DataAPIClient {

    public static void doHttpRequest(Context context, final String url, Map<String, String> params, final DataAPIListener apiListener) {

        Contacts.showProgress(context);

        GetBuilder builder = OkHttpUtils.get().url(url);

        Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();

            String key = entry.getKey();
            String value = entry.getValue();

            builder.addParams(key, value);
        }

        builder.build().execute(new JsonCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Contacts.hideProgress();
                apiListener.onFailure(e.getMessage());
            }

            @Override
            public void onResponse(JSONObject response, int id) {

                Contacts.hideProgress();
                apiListener.onSuccess(response);
            }
        });
    }

    public static void doHttpHeadersRequest(Context context, final String url, Map<String, String> params, final DataAPIListener apiListener) {

        Contacts.showProgress(context);

        GetBuilder builder = OkHttpUtils.get().url(url).addHeader("Authorization","APPCODE " + Contacts.appcode);

        Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();

            String key = entry.getKey();
            String value = entry.getValue();

            builder.addParams(key, value);
        }

        builder.build().execute(new JsonCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Contacts.hideProgress();
                apiListener.onFailure(e.getMessage());
            }

            @Override
            public void onResponse(JSONObject response, int id) {

                Contacts.hideProgress();
                apiListener.onSuccess(response);
            }
        });
    }
}
